import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { RedisService } from 'src/modules/common/services/redis.service';
import { EventToPlayer } from './entities/event-to-player.entity';
import { EventToPlayerService } from './event-to-player.service';
import { groupBy } from 'lodash';
import logger from 'src/common/utils/log';

@Injectable()
export class EventToPlayerCacheService {
  constructor(
    private readonly redisService: RedisService,
    private readonly eventToPlayerService: EventToPlayerService,
  ) {}
  private getListByEventIdKey = 'event-to-player:getListByEventId';

  @OnEvent('event-to-player.update')
  async handleEventToPlayerUpdate(payload: EventToPlayer[]) {
    // const { eventId } = payload;
    const group = groupBy(payload, 'eventId');
    for (const eventId in group) {
      await this.deleteListByEventId(+eventId);
    }
  }

  async getListByEventId(eventId: number) {
    const res = await this.redisService.get(
      `${this.getListByEventIdKey}:${eventId}`,
    );
    if (!res) {
      const list = await this.eventToPlayerService.findByEventId(eventId);
      await this.setListByEventId(eventId, list);
      this.setListByEventId(eventId, list);
      return list;
    }
    return res ? JSON.parse(res) : null;
  }

  async setListByEventId(eventId: number, list: EventToPlayer[]) {
    await this.redisService.set(
      `${this.getListByEventIdKey}:${eventId}`,
      JSON.stringify(list),
    );
  }

  async deleteListByEventId(eventId: number) {
    logger.info(`deleteListByEventId: ${eventId}`);
    await this.redisService.delete(`${this.getListByEventIdKey}:${eventId}`);
  }
}
